#include <stdio.h>
#include <stdlib.h>
#include<sys/wait.h>
#include <unistd.h>
#include <string.h>
#define NUM 128
#define CMD_NUM 64
int main(){
  char* argv[CMD_NUM] = {NULL};
  //1、打印提示符
  char command[NUM];
  while(1){
    command[0] = 0;
    printf("[who@VM-0-13-centos 3-26]$");
    fflush(stdout);
    //2、获取命令字符串
    fgets(command, NUM, stdin);
    command[strlen(command) - 1] = '\0';
    printf("echo: %s\n",command);
    
    //3、解析命令字符串
    const char* sep = " ";
    argv[0] = strtok(command, sep);
    int i = 1;
    while(argv[i] = strtok(NULL, sep)){
      i++;
    }
    for(i = 0; argv[i]; i++){
      printf("argv[%d]---->%s\n",i,argv[i]);
    }
    //4、检测命令是否需要shell本身执行（内建命令）
    if(strcmp(argv[0],"cd") == 0){
      if(argv[1] != NULL){
        chdir(argv[1]);
        continue;
      }
    }
    //5、执行第三方命令
    if(fork() == 0){
      execvp(argv[0],argv);
      exit(1);
    }
    int status = 0;
    waitpid(-1,&status,0);
    printf("exit code: %d\n",(status>>8)&11111111);
    printf("wait success!\n");
  }
  return 0;
}
